package dk.ucn.datamatiker.saveme;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SettingsActivity extends Activity {
	private static final String URL = "http://balder.ucn.dk/dm77_gr2/SaveMe.svc/savenewuser/";
	private EditText homeAddress, phoneNumber;
	private Button okButton;
	private SharedPreferences settings;
	public static final String PREFS_NAME = "saveMeData";
	public static final String HOME_ADDRESS = "homeAddress";
	private SharedPreferences.Editor settingsEditor;
	private URL url;
	private InputStream inputStream;
	private boolean response = false;
	private static final String PHONE_PATTERN = "(\\+\\d{10})|(\\d{8})";
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_layout);
		settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
		homeAddress = (EditText) findViewById(R.id.etHomeAddress);
		phoneNumber = (EditText) findViewById(R.id.etPhonNum);
		okButton = (Button) findViewById(R.id.okButton);

		homeAddress.setText(settings.getString(HOME_ADDRESS, ""));
		if(getIntent().getExtras() != null && getIntent().getStringExtra(SaveMeMainActivity.PHONE_NUMBER) != null){
			phoneNumber.setText(getIntent().getStringExtra(SaveMeMainActivity.PHONE_NUMBER));
		}else{
			if(!settings.getString(SaveMeMainActivity.PHONE_NUMBER, "").equals(""))
			phoneNumber.setText("+" + settings.getString(SaveMeMainActivity.PHONE_NUMBER, ""));
		}

		okButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (homeAddress.getText().length() != 0 && phoneNumber.getText().length() != 0 ) {
					if(phoneNumber.getText().toString().matches(PHONE_PATTERN)){
						settingsEditor = settings.edit();
						settingsEditor.putString(HOME_ADDRESS, homeAddress.getText().toString());
						settingsEditor.putString(SaveMeMainActivity.PHONE_NUMBER, phoneNumber.getText().toString().replace("+", ""));
						settingsEditor.commit();
						
						try {
							Thread thread = new Thread(new Runnable() {
								public void run() {
									//remove + from the phone number when sending to the database
									saveInformation(phoneNumber.getText().toString().replace("+", ""));
								}
							});
							thread.start();
							thread.join();
							if(response){
								Toast.makeText(getApplicationContext(), R.string.details_input_success, Toast.LENGTH_LONG).show();
							}else{
								Toast.makeText(getApplicationContext(), R.string.details_input_fail, Toast.LENGTH_LONG).show();
							}
						} catch (InterruptedException interruptedException) {
							Log.e("SettingsActivity", "okButton", interruptedException);
						}
					}else {
						Toast.makeText(getApplicationContext(), R.string.invalid_phone_number, Toast.LENGTH_LONG).show();
					}
				} else {
					Toast.makeText(getApplicationContext(), R.string.no_input, Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	private void saveInformation(String phoneNumber) {
		try {
			url = new URL(URL + phoneNumber + "-" + homeAddress.getText().toString());
			inputStream = url.openConnection().getInputStream();
			response = Boolean.valueOf(parse(inputStream));
		} catch (MalformedURLException malformedURLException) {
			Log.e("SettingsActivity", "saveInformation()", malformedURLException);
		} catch (IOException e) {
			Log.e("SettingsActivity", "saveInformation()", e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException ioException) {
					Log.e("SettingsActivity", "saveInformation()", ioException);
				}
			}
		}
	}

	private String parse(InputStream inputStream) {
		String result = null;
		boolean found = false;
		try {
			XmlPullParserFactory parserFactory = XmlPullParserFactory.newInstance();
			parserFactory.setNamespaceAware(true);
			XmlPullParser xmlParser = parserFactory.newPullParser();
			xmlParser.setInput(inputStream, null);

			while (xmlParser.getEventType() != XmlPullParser.END_DOCUMENT && !found) {
				if (xmlParser.getEventType() == XmlPullParser.START_TAG) {
					String theTag = xmlParser.getName();
					if (theTag.equals("boolean") && xmlParser.getEventType() != XmlPullParser.END_TAG) {
						result = xmlParser.nextText();
					}
				}
				xmlParser.next();
			}
		} catch (XmlPullParserException e) {
			Log.e("SettingsActivity", "parse", e);
		} catch (IOException e) {
			Log.e("SettingsActivity", "parse", e);
		}
		return result;
	}
}